// pages/search/search.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone:'',
    searchText: '', // 用于存储搜索关键词
    filteredData: [], // 用于存储过滤后的数据
    skuName:'',
    products:[
    
    ],
    currentData:{},
    currentNum:1,
    showModal: false,
    showAuthPopup: false,
    modalAnimation: null,
    maskAnimation: null
  },
    //加入购物车
    addCar: function(e) {
      let productId=e.currentTarget.dataset.id;
      let _this=this;
      wx.request({
        url:app.globalData.onlineUrl+"/addBuyCar",
        header:{'content-type': 'application/json'},
        method:"POST",
        data:{
          phone:_this.data.phone,
          productId:productId,
          buyNum:_this.data.currentNum
        },
        dataType:"json",
        complete:function(result) {
          _this.hideModal();
          wx.showToast({
            title: '加入成功',
            image: '/images/123.png',
            duration: 2000,
            mask:true
          })
          app.getBuyCarNum();
          console.log(888,result.data.data);
        }
      })
    },
  handleInputChange(e) {
    // e.detail.value 是输入框的当前值
    this.setData({
      searchText: e.detail.value, // 更新搜索关键词
    });
    this.performSearch(); // 执行搜索或过滤操作
  },
  performSearch() {
    const filtered = this.data.products.filter(item => item.skuName.includes(this.data.searchText)); // 假设你想根据某个属性进行搜索
    this.setData({
      filteredData: filtered // 更新过滤后的数据列表
    });
  },
  // 增加数量
  increaseQuantity() {
    if(this.data.currentNum<this.data.currentData.inventory){
      this.data.currentNum++;
      this.setData({
        currentNum:this.data.currentNum
      });
    }
  },

  // 减少数量
  decreaseQuantity() {
    if(this.data.currentNum>1){
      this.data.currentNum--;
      this.setData({
        currentNum:this.data.currentNum
      });
    }
  },
    //2.0跳转商品详情
    gotoProductDetail:function(e){
      wx.navigateTo({
        url: '/pages/productDetails/productDetails?id='+e.currentTarget.dataset.id
      })
    },
      //获取商品列表
      getProduct:function(){
        let _this=this;
        wx.request({
          url:app.globalData.onlineUrl+"/productNew/list",
          header:{'content-type': 'application/json'},
          method:"POST",
          data:{type:0,skuName:this.data.skuName},
          dataType:"json",
          complete:function(result) {
            console.log(9999,result.data.data);
            let data=result.data.data;
            _this.setData({
              products:data,
              filteredData:data,
            })
          }
        })
      },


    // 2.0打开弹窗
showModal(e) {
  if(this.data.phone){
    this.setUser();
    // 创建动画
    const modalAnimation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease-out'
    })
    
    const maskAnimation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease-out'
    })

    // 执行动画
    maskAnimation.opacity(1).step()
    modalAnimation.translateY(0).step()
    const currentData = this.data.products.find(item => item.id === e.currentTarget.dataset.id);
    this.setData({
      currentData:currentData,
      showModal: true,
      modalAnimation: modalAnimation.export(),
      maskAnimation: maskAnimation.export()
    })
  }else{
    this.setData({ showAuthPopup: true });
  }
},

hideModal() {
  const modalAnimation = wx.createAnimation({
    duration: 250,
    timingFunction: 'ease-in'
  })
  
  const maskAnimation = wx.createAnimation({
    duration: 250,
    timingFunction: 'ease-in'
  })

  maskAnimation.opacity(0).step()
  modalAnimation.translateY('100%').step()

  this.setData({
    modalAnimation: modalAnimation.export(),
    maskAnimation: maskAnimation.export()
  })

  // 延迟隐藏保证动画完成
  setTimeout(() => {
    this.setData({ showModal: false })
  }, 250)
},
jumpYd:function(e){
  console.log(66,e.currentTarget.dataset.id)
  wx.navigateTo({
    url: '/pages/ydhf/ydhf?url='+e.currentTarget.dataset.id
  })
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getProduct();
    this.setData({
      phone:wx.getStorageSync('phone'),
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onGetPhoneNumber(e) {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      const { encryptedData, iv } = e.detail;
      wx.login({
        success: res => {
          if (res.code) {
            // 发送 res.code 到后台换取 openid, session_key, unionid
            wx.request({
              url: app.globalData.onlineUrl+"/getUserPhone", // 替换为你的服务器地址
              header:{'content-type': 'application/json'},
              method: 'POST',
              data: {
                code: res.code,
                encryptedData:encryptedData,
                iv:iv,
              },
              success: (response) => {
                console.log(10086,response.data.data.phoneNumber);
                // 存储用户信息
                wx.setStorageSync('phone', response.data.data.phoneNumber);
                wx.setStorageSync('openid', response.data.data.openId);
                this.setUser();
                this.setData(
                  {
                    phone:wx.getStorageSync('phone'),
                    showAuthPopup:false
                  }
                )
              }
            });
          } else {
            console.log('登录失败！' + res.errMsg);
          }
        }
      });
    } else {
      // 用户拒绝授权时的处理（根据合规要求，建议允许用户取消）
      wx.showToast({ 
        title: '需要授权手机号才能使用完整服务', 
        icon: 'none',
        duration: 2000
      });
    }
  },
  setUser:function(){
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/setUser",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{
        phone:wx.getStorageSync('phone'),
        openId:wx.getStorageSync('openid')
      },
      dataType:"json",
      complete:function(result) {
        console.log("用户信息更新成功");
      }
    })
  },
  onClosePopup() {
    this.setData({ showAuthPopup: false });
  },
})